//
//  TimeSetViewController.m
//  LiTingFeng
//
//  Created by xinxuan on 16/1/16.
//  Copyright © 2016年 Bullgo. All rights reserved.
//

#import "TimeSetViewController.h"
#import "PopupView.h"
#import "TXSaveUsrSetting.h"
#import "LewPopupViewAnimationFade.h"
#import "TimeSetViewController.h"
#import "TrianDataBaseHandel.h"
#import "RemindTableViewCell.h"
@interface TimeSetViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic, strong) NSMutableArray *modelsArray;


//开启提醒开关
@property (weak, nonatomic) IBOutlet UIButton *warnSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *timeSwitch;

@property (nonatomic,strong)TimeSetViewController * remindVC;
@property (nonatomic,strong)UILocalNotification * localNotication;
@property (weak, nonatomic) IBOutlet UIButton *timeButton;

//显示提醒时间
@property (weak, nonatomic) IBOutlet UILabel *timeLable;
/** 时间选择器 */
@property (nonatomic, strong) UIDatePicker *myDatePicker;

@end

@implementation TimeSetViewController
static NSString *ID = @"cell";
- (void)viewDidLoad {
    [super viewDidLoad];
    [self getModelWithTitle];
    
    [self.view addSubview:self.tableView];
    _remindVC = [[TimeSetViewController alloc]init];
    
    [self.timeButton addTarget:self action:@selector(timeButtonOnClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (IBAction)timeSwitch:(UISwitch *)sender {
    
    [[TXSaveUsrSetting shareduserSetting] setUsr_warnWriteState:self.warnSwitch.selected];
    [[TXSaveUsrSetting shareduserSetting] synchronized];
    if (sender.isOn) {
        NSLog(@"本地推送开关开启");
        _localNotication.repeatInterval = kCFCalendarUnitDay;
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Bluetooth"];
        [[NSUserDefaults standardUserDefaults] synchronize];

    }else{
        NSLog(@"本地推送关闭开关");
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"Bluetooth"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        // 取消通知
        _localNotication.repeatInterval = 0;//等于0 ，即不重复
        if (_localNotication != nil) {
            [[UIApplication sharedApplication] cancelAllLocalNotifications];

        }
    }
    
    
}



#pragma mark ---- 懒加载
-(UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.viewTop.constant + 2 * self.viewHeight.constant + 5, Screen_Width, Screen_Height - 40)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = 0;
//        _tableView.backgroundColor = [UIColor clearColor];
        [_tableView registerNib:[UINib nibWithNibName:@"RemindTableViewCell" bundle:nil] forCellReuseIdentifier:ID];
    }
    return _tableView;
}

-(void)getModelWithTitle{
    _modelsArray = [NSMutableArray array];
    
    _modelsArray = [[TrianDataBaseHandel shareManager]fetchAllData];
    
    
}




- (void)timeButtonOnClick:(UIButton*)sender
{
    if (!self.timeSwitch.isOn) {
        // 提示没有开启提醒开关

        [self openWarnSwitch];
 
    }else{
        if (self.myDatePicker.superview == nil) {
            NSLog(@"已经打开提醒开关");
            [self setupDatePicker];
        }
        
    }
   
}





#pragma mark -- 提示打开提醒开关
- (void)openWarnSwitch{
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, Screen_Height/2, 150, 30)];
    label.alpha = 0.0;
    [self.view addSubview:label];
    [UIView animateWithDuration:1.0 animations:^{
        label.frame = CGRectMake(100, Screen_Height/2, 150, 30);
        label.text = @"请先打开提醒开关";
        label.layer.masksToBounds = YES;
        label.layer.cornerRadius = 5;
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor colorWithWhite:0.377 alpha:1.000];
        label.alpha = 1.0;
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:3 animations:^{
            label.alpha = 0.0;
        }];
        [label removeFromSuperview];
    }];
    
}



#pragma mark -- 时间选择器

- (void)setupDatePicker{
    
    PopupView *view = [PopupView defaultPopupView];
    self.myDatePicker = view.datePicker;
    
    view.parentVC = self;
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationFade new] dismissed:^{
        NSLog(@"动画结束");
    }];
    [self.myDatePicker addTarget:self action:@selector(chooseDate:) forControlEvents:(UIControlEventValueChanged)];
    
    
}

// 获取时间选择器上的时间
- (void)chooseDate:(UIDatePicker *)myDatePicker{
    
    NSDate *selectDate = myDatePicker.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    NSString *dateString = [formatter stringFromDate:selectDate];
    self.timeLable.text = dateString;
    
    [[TXSaveUsrSetting shareduserSetting] setUsr_warnWriteTime:dateString];
    [[TXSaveUsrSetting shareduserSetting] synchronized];
    
    [self scheduleLocalNotificationWithDate:self.myDatePicker.date];
    NSLog(@"调用本地通知");
}




#pragma mark -- 调用本地通知
- (void)scheduleLocalNotificationWithDate:(NSDate *)fireDate{
    
    if (_localNotication != nil) {
        
        [[UIApplication sharedApplication] cancelLocalNotification:_localNotication];
    }
    // 定义本地通知
    _localNotication = [[UILocalNotification alloc] init];
    _localNotication.alertAction = @"打开应用"; // 待机界面的滑动动作提示
    //    _localNotication.applicationIconBadgeNumber = 1;
    NSArray *bodyArray = @[@"万物皆萌,该写日记了", @"世界很美，而你正好有空，快去记录把", @"快乐是首歌，除了唱还可以写哦[写日记去]", @"Life is a song! Go to Write", @"帮你记录心情是我生命里程中的唯一目的[马上写日记]", @"天若有情，亘古不老,该写日记了", @"一万个美丽的未来，也比不上一个温暖的现在[写日记去]", @"今天是什么颜色？[我要写日记]", @"碧水青山终行遍，不及一缕情丝相思缠[写日记]"];
    NSInteger bodyArray_i = (arc4random()%(8-0+1)) + 0;
    NSLog(@"%ld", (long)bodyArray_i);
    _localNotication.alertBody = bodyArray[bodyArray_i];
    _localNotication.fireDate = fireDate;
    _localNotication.soundName = UILocalNotificationDefaultSoundName;
    
    // 设置通知重复次数
    _localNotication.repeatInterval = kCFCalendarUnitDay;
    
    //notication.alertLaunchImage = @"Default"; // 通过点击通知打开应用时的启动图片
    
    [[UIApplication sharedApplication] scheduleLocalNotification:_localNotication];
    
}







// 懒加载
- (UIDatePicker *)myDatePicker{
    
    if (!_myDatePicker) {
        self.myDatePicker = [[UIDatePicker alloc] init];
    }
    return _myDatePicker;
}



-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    self.timeLable.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"time"];
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"Bluetooth"])
    {
        if(!_timeSwitch.isOn)
        {
            [_timeSwitch setOn:YES animated:YES];
        }
    }
    else
    {
        if(_timeSwitch.isOn)
        {
            [_timeSwitch setOn:NO animated:YES];
        }
    }
   

}


-(void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
    NSString *dataString = [[TXSaveUsrSetting shareduserSetting] warnTimeString];
    self.timeLable.text = dataString;
    [[NSUserDefaults standardUserDefaults] setObject:dataString forKey:@"time"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


-(void)viewDidAppear:(BOOL)animated{

   

}



//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    
//    return 40;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48;
    
}

//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//    
//    
//    return @"提醒周期";
//    
//}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%ld",_modelsArray.count);
    return _modelsArray.count;
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    RemindTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    CommenModel * remindMode = _modelsArray[indexPath.row];
    cell.nameLabel.text = remindMode.name;
    NSLog(@"%@",remindMode.starCount);
    [cell.starView addStarViewWithCount:[remindMode.starCount intValue]];
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CommenModel * model = [CommenModel new];
    model = _modelsArray[indexPath.row];
    NSLog(@"%@",model);
    
    TrainViewController * trainVc = [[TrainViewController alloc] init];
    trainVc.model = model;
    trainVc.nameString = model.name;
    trainVc.detailString = model.centent;
    trainVc.totalTime = [model.time integerValue] * 60;
    [self.navigationController pushViewController:trainVc animated:YES];
    
    
}



#pragma mark --------TableView 编辑-----------

//第一步,使处于可编辑状态

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    
    [self.tableView setEditing:editing animated:animated];
    
    self.navigationItem.rightBarButtonItem.title = editing?@"完成":@"删除";
    
}


//第二步,指定那些路径可以被编辑

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
    
}





//第三步,指定编辑样式

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

//第四步,完成编辑

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        CommenModel * model = _modelsArray[indexPath.row];
        
        [[TrianDataBaseHandel shareManager]deleteData:model];
        
        [_modelsArray removeObject:model];
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationLeft)];
        
        [self.tableView reloadData];
        
        
    }
}

@end
